<?php
namespace app\admin\controller\dividend;
use app\admin\controller\Controller;
use app\admin\model\dividend\Dividend as DividendModel;
use think\Db;
use OSS\OssClient;
use OSS\Core\OssException;
/**
 * 自营公司管理
 */
class System extends Controller{
    /**
     * 首页
     */
    public function index(){
        $model = new DividendModel();
        return $this->fetch('index', [
            //自营公司列表
            'list' => $list = $model->getList($this->request->param(),1),

        ]);
    }
    /**
     * 添加自营公司
     */
    public function add(){
        $model = new DividendModel;
        if (!$this->request->isAjax()) {
            return $this->fetch('add');
        }
        $admin=$this->postData('admin');
        // 新增记录
        if (!preg_match("/^1[345789]\d{9}$/", $this->postData('company')['phone'])) {
            return $this->renderError($model->getError() ?: '手机号格式不正确');
        }
        if($model->add($this->postData('company'),$admin)){
            return $this->renderSuccess('添加成功', url('dividend.system/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }
    /**
     * 编辑自营公司信息
     */
    public function edit($id){
        //公司详情
        $model = DividendModel::detail($id);
        //登录信息
        $loginInfo=Db::name('yonghui_adminuser')->where(['companyId'=>$model->id])->find();
        if (!$this->request->isAjax()){
            return $this->fetch('edit', compact('model','loginInfo'));
        }
        //更新记录
        if (!preg_match("/^1[345789]\d{9}$/", $this->postData('company')['phone'])) {
            return $this->renderError($model->getError() ?: '手机号格式不正确');
        }
        if ($model->edit($this->postData('company'),$id)){
            return $this->renderSuccess('更新成功', url('dividend.system/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }
    /**
     * 删除
     */
    public function delete($id){
        $model = DividendModel::detail($id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        //将登录账号也禁用
        Db::name('yonghui_adminuser')->where(['companyId'=>$id])->update(['status'=>2]);
        return $this->renderSuccess('删除成功');
    }
    /**
     * 恢复
     */
    public function recover($id){
        $model = DividendModel::detail($id);
        if (!$model->setrecover()) {
            return $this->renderError($model->getError() ?: '恢复失败');
        }
        //将登录账号也恢复
        Db::name('yonghui_adminuser')->where(['companyId'=>$id])->update(['status'=>1]);
        return $this->renderSuccess('恢复成功');
    }
    public function upload(){
        return $this->fetch('upload');
    }

    /*
     * 上传测试
     */
    public function uploadFile($savedir = './video'){
        $name='newfile';
        $return_arr = array('0','');
        $userID = 1; //用户标识
        if(!empty($_POST['act']) && trim($_POST['act'])=='combine'){
            //合并文件
            $chunks = intval($_POST['chunks']);//总分块个数
            $time = intval($_POST['time']);
            //文件后缀
            $type = substr($_POST['filename'],strripos($_POST['filename'],'.'));
            //限制文件格式
//            if (!in_array($type,['.mp4','.avi'])) {
//                abort(403, '文件格式不允许', []);
//            }
            //保存临时文件
            $tmppath = $savedir.'/tmp'; //临时目录,
            if(!file_exists($tmppath)){ @mkdir($tmppath,0777,true); }
            $filenamemd5 = md5($_POST['filename'].$time);
            $savedir = $savedir.'/files/'.date('Ym',time());
            if(!file_exists($savedir)){ @mkdir($savedir,0777,true);}
            $newname = date('mdH',time()).rand(10000,99999).'_'.rand(100000,999999).$type;
            $writer = fopen("{$savedir}/{$newname}","ab"); //合并后的文件名
            for($i=0;$i<$chunks;$i++){
                $file2read = "{$tmppath}/{$userID}_{$filenamemd5}_{$i}";
                $reader = fopen($file2read,"rb");
                fwrite($writer,fread($reader,filesize($file2read)));
                fclose($reader);
                unset($reader);
                @unlink($file2read);//删除分块临时文件
            }
            fclose($writer);
            //上传整个文件夹
            $prefix = "samples/codes";
            $ossClient = new OssClient('LTAI5tARxhHb7AZZGqSXSEYZ', 'OUik8AMQxuR1Wn05WSytnjDNcCYW33', 'http://oss-cn-beijing.aliyuncs.com');
            $ossClient->uploadDir('yonghuilianbang', $prefix, $savedir);
            //删除本地文件
            $a="{$savedir}/{$newname}";
            @unlink($a);


            $return_arr['flag']='1';
            $return_arr[1]="{$savedir}/{$newname}";
        }else{
            if(empty($_FILES[$name]) || $_FILES[$name]["error"] > 0){
                return array( '0','上传失败' );
            }
            //保存临时文件
            $chunks = intval($_POST['chunks']);//总分块个数
            $chunk  = intval($_POST['chunk']);//当前分块索引
            $time = intval($_POST['time']);
            //临时目录
            $tmppath = $savedir.'/tmp';
            if(!file_exists($tmppath)){ @mkdir($tmppath,0777,true); }
            $filenamemd5 = md5($_POST['filename'].$time);
            $tmpname = "{$userID}_{$filenamemd5}_{$chunk}";//临时文件名
            @move_uploaded_file($_FILES[$name]["tmp_name"],"{$tmppath}/{$tmpname}");
            $return_arr['flag']='1';
            $return_arr[1]='';
        }

        return $return_arr;
    }
}